/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cmp.arena.controls;

import com.cmp.player.controls.CharacterRigidBodyControl;
import com.jme3.bullet.control.GhostControl;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.AbstractControl;
import com.jme3.scene.control.Control;

/**
 * Handles ownership, spawning and possibly throwing of the ball.
 * lets make this reusable for all kinds of maps. 
 * @author krummer
 */
public class BallControl extends AbstractControl {
    private Vector3f spawnPos;
    private Node parentMap;
    private CharacterRigidBodyControl body;
    
    public void attachToMap() {
        if(body != null) {
            Vector3f pos = super.getSpatial().getWorldTranslation().clone();
            this.getSpatial().removeFromParent();
            this.parentMap.attachChild(super.getSpatial());
            super.getSpatial().getControl(GhostControl.class).setEnabled(true);
            this.body.setEnabled(true);
            this.body.activate();
            this.body.setPhysicsLocation(pos);
            this.body.getMotionState().applyTransform(super.getSpatial());
        }
        
    }
    
    public void respawn() {
        this.attachToMap();
        this.body.setPhysicsLocation(this.spawnPos);
        this.body.getMotionState().applyTransform(super.getSpatial());
    }
    
    public void attachTo(Node attachee) {
        attachee.attachChild(super.getSpatial());
    }
    
    public Node getParentMap() {
        return this.parentMap;
    }
    public void setSpawnPos(Vector3f pos) {
        this.spawnPos = pos;
    }
    
    @Override
    public void setSpatial(Spatial spatial) {
        super.setSpatial(spatial);
        this.parentMap = spatial.getParent();
        body = spatial.getControl(CharacterRigidBodyControl.class);
    }
    
    @Override
    protected void controlUpdate(float tpf) {
    }

    @Override
    protected void controlRender(RenderManager rm, ViewPort vp) {
    }

    public Control cloneForSpatial(Spatial spatial) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
}
